#include <stdlib.h>
#include <stdio.h>

void init(int mask[5][9], int ip[5][9])
{
	int i,j;
	for(i=0; i<4; i++)
		for(j=0; j<8; j++)
		{
			mask[i][j] = 0;
			ip[i][j] = 0;
		}
}

void get_array (int array[5][9], char* str)
{
	int tmp=0;
	int old=0;
	int num_r;
	int i,j;
	for (i=0; i<strlen(str); i++)
	{
		if (str[i] == '.')
		{
			char num[10];
		 	strncpy(num,str+old,i-old);
			num[i-old]=0;
			sscanf(num,"%d",&num_r);
			int sum=0;
			int top=128;
			for(j=0; j<8; j++)
			{
				if(sum + top <= num_r)
				{
					array[tmp][j]=1;
				        sum=sum+top;
				}
				top=top/2;
			}
			tmp++;
			old = i+1;				
			continue;
		}
		if (i==strlen(str)-1)
		{
			char num[10];
			strncpy(num,str+old,i-old+1);
			num[i-old+1]=0;
                        sscanf(num,"%d",&num_r);
                        int sum=0;
			int top=128;
                        for(j=0; j<8; j++)      
                        {
                                if(sum + top <= num_r)array[tmp][j]=1;                                          sum=sum+top;
                                top=top/2;
                        }       
                        break;
                }

	}
}
		
int main(int argc,char *argv[])
{

	int mask[5][9];
	int ip[5][9];
	int tmp[5][9];
	char get_par[16];
	int i, j;
	FILE *fp=NULL;
	int num[4];
	char gateway[16],ip_from[16],ip_to[16];
	init(mask, ip);
	strcpy(get_par, argv[1]);
	get_array(mask, get_par);
	strcpy(get_par, argv[2]);
 	get_array(ip, get_par);
	for (i=0; i<4; i++)
                for(j=0; j<8; j++)
			tmp[i][j] = ip[i][j];
	for (i=0; i<4; i++)
		for(j=0; j<8; j++)
		{
			if(mask[i][j] == 0)tmp[i][j] = 0;
		}
	for (i=0; i<4; i++)
	{
		num[i] = 0;
		int top=128;
		for(j=0; j<8; j++)
		{
			num[i]+=tmp[i][j]*top;
			top=top/2;
		}
	}
	num[3]++;
	sprintf(gateway,"%d.%d.%d.%d",num[0],num[1],num[2],num[3]);
	sprintf(ip_from,"%d.%d.%d.%d",num[0],num[1],num[2],num[3]+1);
	for (i=0; i<4; i++)
                for(j=0; j<8; j++)
                {
                        if(mask[i][j] == 0)tmp[i][j] = 1;
                }
        for (i=0; i<4; i++)
        {
                num[i] = 0;
                int top=128;
                for(j=0; j<8; j++)
                {
                        num[i]+=tmp[i][j]*top;
                        top=top/2;
                }
        }
	sprintf(ip_to,"%d.%d.%d.%d",num[0],num[1],num[2],num[3]-1);
	if((fp=fopen("/root/xen/vm_ops_scripts/bridge/info.txt","w+"))==NULL)
        {
                printf("cannot open file!\n");
                exit(0);
        }
	fputs("gateway ",fp);
	fputs(gateway,fp);
	fputs("\n",fp);
	fputs("ip_from ",fp);
        fputs(ip_from,fp);
        fputs("\n",fp);
        fputs("ip_to ",fp);
        fputs(ip_to,fp);
        fputs("\n",fp);

	return 0;
}	
